import { GetInfoPicture, GetIssueReceiptInfo, GetPreviewImage, PostDeleteData, PostInfoPicture, PostIssueReceiptInfo } from "/constData/requestFun/_httpRequest";
import isEmpty from 'loadsh/isEmpty'
import { GetContractManagement, GetContractManagementById, GetIssueReceipts, GetIssueReceiptsById, IssueReceiptsDeleteData, PostIssueReceipts } from "/constData/requestFun/_teseRequest";
import compact from 'loadsh/compact'
import { CORPID, SPACEID } from '/constData/requestFun/_globalData';
Page({
  data: {
    item: 1,
    min: null,
    max: new Date('2033/12/02'),
    defaultDate: null,
    receiptsinfo: {
      CorpId: '',//申请人
      InvoiceType: '',//开收据类型
      ApplicantDepart: '',//申请部门
      ReasonReceipt: '', //开收据事由
      ReceiptAmount: '',//开收据金额
      ReceiptDate: '',//开收据日期
      ReceiptCompany: '',//开收据公司名称
      Annex: '[]', //附件
      LargeAmount: '',
    },
    list: ['流片', '测试', 'EDA', '孵化', '常规'],
    ReceiveData: [],
    displaydata: [],
    ContractRelevancyData: [],
    ContractRelevancyDisplayData: [],
    Name: '',//申请人姓名
  },
  selectorProjectContract(e) {
    const data = e.target.dataset.data
    const newAssociateOtherIds = [
      ...JSON.parse(this.data.receiptsinfo.AssociateOtherId || '[]'), // 将字符串转换为数组，如果为空则使用空数组  
      data.item1.id // 添加新的ID到数组中  
    ];
    this.setData({
      ContractRelevancyDisplayData: [...this.data.ContractRelevancyDisplayData, data],
      receiptsinfo: {
        ...this.data.receiptsinfo,
        AssociateOtherId: JSON.stringify(newAssociateOtherIds) // 将数组转换回字符串，以符合您当前的数据结构  
      }
    })
    my.alert({
      title: '添加成功',
    });
  },
  handlePopupClose() {
    this.setData({
      basicVisible: false,
      scrollVisible: false,
      closeVisible: false,
    });
  },
  handleShowClose() {
    this.setData({
      closeVisible: true
    });
  },
  handleShowBasic(e) {
    var position = e.target.dataset.position;
    this.setData({
      position: position,
      basicVisible: true,
    });
    my.getStorage({
      key: 'userInfo',
      success: (storage) => {
        GetContractManagement((res) => {
          const cacheData = res.data.map(it => {
            if (it.item1.corpId === storage.data.result.userid) {
              it.item1['displayPicture'] = JSON.parse(it.item1.picture)
              it.item1['displayApprovalAnnex'] = JSON.parse(it.item1.approvalAnnex)
              return it
            }
          })
          this.setData({
            ContractRelevancyData: compact(cacheData).reverse()
          })
        })
      }
    })
  },
  Delete(e) {
    const id = e.currentTarget.dataset.id
    IssueReceiptsDeleteData(id, (res) => {
      my.alert({
        title: '撤销成功',
      });
      //刷新数据
      this.setData({
        ReceiveData: this.data.ReceiveData.filter((it) => {
          return it.item1.id !== id
        })
      })
    }, (err) => {
      my.alert({
        title: '撤销失败',
      });
    })
  },
  OnInvoiceType(value) {
    this.setData({
      receiptsinfo: {
        ...this.data.receiptsinfo,
        InvoiceType: value
      }
    })
  },
  onApplicatDepartChange(value) {
    this.setData({
      receiptsinfo: {
        ...this.data.receiptsinfo,
        ApplicantDepart: value
      }
    })
  },
  onReasonReceiptChange(value) {
    this.setData({
      receiptsinfo: {
        ...this.data.receiptsinfo,
        ReasonReceipt: value
      }
    })
  },
  onReceiptAmountChange(e) {
    this.setData({
      receiptsinfo: {
        ...this.data.receiptsinfo,
        ReceiptAmount: e,
        LargeAmount: intToChinese(e)
      }
    })
  },
  onReceiptCompanyChange(value) {
    this.setData({
      receiptsinfo: {
        ...this.data.receiptsinfo,
        ReceiptCompany: value
      }
    })
  },
  handleOk(date, format, e) {
    this.setData({
      receiptsinfo: {
        ...this.data.receiptsinfo,
        ReceiptDate: date,
      }
    })
  },
  //获取数据
  onLoad() {
    my.getStorage({
      key: 'userInfo',
      success: (storage) => {
        new Promise((resolve) => {
          GetIssueReceipts((res) => {
            const cacheData = res.data.map(it => {
              if (it.item1.corpId === storage.data.result.userid) {
                it.item1['displayAnnex'] = JSON.parse(it.item1.annex)
                return it;
              }
            });
            resolve(cacheData);
          });
        }).then((cacheData) => {
          const updatedResPromises = cacheData.map(it => {
            // 将 associateOtherId 从字符串转换为数组，如果是 '[]' 则转换为空数组  
            const associateIds = (typeof it.item1.associateOtherId === 'string' && it.item1.associateOtherId === '[]') ? [] : JSON.parse(it.item1.associateOtherId);
            it.item3 = []
            if (it.item1.corpId === storage.data.result.userid && associateIds.length > 0) {
              // 对每个 associateId 
              return Promise.all(associateIds.map(associateId => {
                return new Promise((resolve) => {
                  GetContractManagementById(associateId, (EvectionRes) => {
                    it.item3.push(EvectionRes.data.item1)
                    resolve(it);
                  });
                });
              })).then(() => it); // 所有 Topic 获取完毕后返回当前对象  
            } else {
              // 如果 associateIds 为空或 it.item1.corpId 不匹配，则直接返回当前对象  
              return Promise.resolve(it);
            }
          });
          // 等待所有 Promise 完成  
          return Promise.all(updatedResPromises).then(updatedRes => {
            this.setData({
              receiptsinfo: {
                ...this.data.receiptsinfo,
                CorpId: storage.data.result.userid
              },
              ReceiveData: compact(updatedRes).reverse(),
              Name: storage.data.result.name
            });
          });
        });
      }
    });
    // my.getStorage({
    //   key: 'userInfo',
    //   success: (storage) => {
    //     GetIssueReceipts((res) => {
    //       const cacheData = res.data.map(it => {
    //         if (it.item1.corpId === storage.data.result.userid) {
    //           it.item1['displayAnnex'] = JSON.parse(it.item1.annex)
    //           return it
    //         }
    //       })
    //       this.setData({
    //         receiptsinfo: {
    //           ...this.data.receiptsinfo,
    //           CorpId: storage.data.result.userid
    //         },
    //         ReceiveData: compact(cacheData).reverse(),
    //         Name: storage.data.result.name
    //       })
    //     })
    //   }
    // })
  },
  // 上传数据
  onSubmit(e) {
    PostIssueReceipts(JSON.stringify(this.data.receiptsinfo),
      (res) => {
        my.alert({
          title: '提交成功',
        });
        GetIssueReceiptsById(res.data, (res) => {
          this.setData({
            ReceiveData: compact([...this.data.ReceiveData, res.data].map(it => {
              if (it.item1.corpId === this.data.receiptsinfo.CorpId) {
                it.item1['displayAnnex'] = JSON.parse(it.item1.annex)
                return it
              }
            })).reverse()
          })
        })
        this.setData({
          receiptsinfo: {
            ...this.data.receiptsinfo,
            ApplicantDepart: '',//申请部门
            ReasonReceipt: '', //开收据事由
            ReceiptAmount: '',//开收据金额
            ReceiptDate: '',//开收据日期
            ReceiptCompany: '',//开收据公司名称
            Annex: '[]', //附件
          }
        })
      },
      (err) => {
        my.alert({
          title: '提交成功1',
        });
      })
  },

  //上传文件
  onUpload() {
    let imageAnnex = ''
    dd.uploadAttachmentToDingTalk({
      image: {
        max: 9,
        spaceId: SPACEID,
        compress: true,
        folderId: '',
        multiple: true,
      },
      file: { spaceId: SPACEID, max: 9, folderId: '' },
      types: ['photo', 'file'],
      success: (res) => {
        const srcAnnex = this.data.receiptsinfo.Annex
        imageAnnex = res.data
        imageAnnex.push(...JSON.parse(srcAnnex))
        this.setData({
          displaydata: imageAnnex,
          receiptsinfo: {
            ...this.data.receiptsinfo,
            Annex: JSON.stringify(imageAnnex)
          }
        })
      },
      fail: () => { },
      complete: () => { },
    });
  },
  PreviewBtn(e) {
    const item = e.currentTarget.dataset.item
    dd.previewFileInDingTalk({
      spaceId: item.spaceId,
      fileName: item.fileName,
      corpId: CORPID,
      fileSize: item.fileSize,
      fileType: item.fileType,
      fileId: item.fileId,
    });
  },
  CheckPictures(e) {
    const item = e.currentTarget.dataset.item
    dd.previewFileInDingTalk({
      spaceId: item.spaceId,
      fileName: item.fileName,
      corpId: CORPID,
      fileSize: item.fileSize,
      fileType: item.fileType,
      fileId: item.fileId,
    });
  },
});
function intToChinese(money) {
  //汉字的数字
  var cnNums = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
  //基本单位
  var cnIntRadice = ['', '拾', '佰', '仟'];
  //对应整数部分扩展单位
  var cnIntUnits = ['', '万', '亿', '兆'];
  //对应小数部分单位
  var cnDecUnits = ['角', '分', '毫', '厘'];
  //整数金额时后面跟的字符
  var cnInteger = '整';
  //整型完以后的单位
  var cnIntLast = '元';
  //最大处理的数字
  var maxNum = 999999999999999.9999;
  //金额整数部分
  var integerNum;
  //金额小数部分
  var decimalNum;
  //输出的中文金额字符串
  var chineseStr = '';
  //分离金额后用的数组，预定义
  var parts;
  if (money === '') { //不能用==
    return '';
  }
  money = parseFloat(money);
  if (money >= maxNum) {
    //超出最大处理数字
    return '';
  }
  if (money == 0) {
    chineseStr = cnNums[0] + cnIntLast + cnInteger;
    return chineseStr;
  }
  //转换为字符串
  money = money.toString();
  if (money.indexOf('.') == -1) {
    integerNum = money;
    decimalNum = '';
  } else {
    parts = money.split('.');
    integerNum = parts[0];
    decimalNum = parts[1].substr(0, 4);
  }
  //获取整型部分转换
  if (parseInt(integerNum, 10) > 0) {
    var zeroCount = 0;
    var IntLen = integerNum.length;
    for (var i = 0; i < IntLen; i++) {
      var n = integerNum.substr(i, 1);
      var p = IntLen - i - 1;
      var q = p / 4;
      var m = p % 4;
      if (n == '0') {
        zeroCount++;
      } else {
        if (zeroCount > 0) {
          chineseStr += cnNums[0];
        }
        //归零
        zeroCount = 0;
        chineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
      }
      if (m == 0 && zeroCount < 4) {
        chineseStr += cnIntUnits[q];
      }
    }
    chineseStr += cnIntLast;
  }
  //小数部分
  if (decimalNum != '') {
    var decLen = decimalNum.length;
    for (var i = 0; i < decLen; i++) {
      var n = decimalNum.substr(i, 1);
      if (n != '0') {
        chineseStr += cnNums[Number(n)] + cnDecUnits[i];
      }
    }
  }
  if (chineseStr == '') {
    chineseStr += cnNums[0] + cnIntLast + cnInteger;
  } else if (decimalNum == '') {
    chineseStr += cnInteger;
  }
  return chineseStr;
}